package com.cqie.tes.config.jwt;

import com.alibaba.fastjson.JSON;
import com.cqie.tes.comm.R;
import com.cqie.tes.config.MyUserDetile;
import com.cqie.tes.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        MyUserDetile userDetails = (MyUserDetile)authentication.getPrincipal();//拿到登录用户信息
        String jwtToken = jwtUtils.generateToken(userDetails.getUsername());//生成token
        MyUserDetile userDetile = (MyUserDetile) authentication.getPrincipal();

        R result = R.ok().data("access_token",jwtToken).data("user",userDetile).message("登录成功");

        httpServletResponse.setCharacterEncoding("UTF-8");//设置编码格式
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSON.toJSONString(result));
        httpServletResponse.getWriter().flush();
   }
}
